import subprocess
import requests
import schedule
import time
import os
import logging
import datetime

# nohup python3 ServerRequest.py > ServerRequest.log &
# 配置日志记录
logging.basicConfig(filename='ServerRequest.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def send_message(message):
    webhook_url = 'https://oapi.dingtalk.com/robot/send?access_token=d366870467b530aec25ef29d0be7345e19c44a6be8834518bba0ab9d5539c4f2'
    headers = {'Content-Type': 'application/json'}
    data = {
        "msgtype": "text",
        "text": {
            "content": message
        }
    }
    response = requests.post(webhook_url, json=data, headers=headers, timeout=5)
    if response.status_code == 200:
        logging.info(message)
        print("消息发送成功")
    else:
        print("消息发送失败")


def get_public_ip():
    response = requests.get('https://api.ipify.org?format=json')
    if response.status_code == 200:
        data = response.json()
        public_ip = data['ip']
        return public_ip
    else:
        return None

def check_website_status(url):
    public_ip = get_public_ip()
    try:
        response = requests.get(url, timeout=5)
        status_code = response.status_code
        if status_code != 200:
            message = f"k8s外网监控： 节点<{public_ip}> ServerRequest {url} returned status code: {status_code}"
            return send_message(message)
        logging.info(f"k8s外网监控： 节点<{public_ip}> ServerRequest {url} returned status code: {status_code}")
    except requests.RequestException as e:
        message = f"k8s外网监控异常消息：节点<{public_ip}> An ServerRequest error occurred while accessing website {url}: {str(e)}"
        send_message(message)


while True:
    # 检查网站状态
    check_website_status("https://www.obsbot.com")

    # 暂停执行2小时
    time.sleep(2 * 60 * 60)
